#include <bits/stdc++.h>

using namespace std;
using ll = long long;
const ll MOD = 998244353;

// 树状数组
class BIT {
public:
	BIT(int size) : size_(size), tree_(size + 1, 0) {}

	void update(int index, int delta) {
		for (int i = index + 1; i <= size_; i+= (i & -i)) {
			tree_[i] += delta;
		}
	}

	int query(int index) {
		int sum = 0;
		for (int i = index + 1; i > 0; i -= (i & -i)) {
			sum += tree_[i];
		}
		return sum;
	}

	int queryRange(int left, int right) {
		return query(right) - query(left - 1);
	}
private:
	int size_;
	vector<int> tree_;
};

void solve() {
	ll n;
	cin >> n;
	vector<int> cnt(n + 1);
	for (ll i = 1, x; i <= n; i++) {
		cin >> x;
		cnt[x]++;
	}
	int ans = 0;
	BIT S(n + 1), C(n + 1);
	for (int i = 1; i <= n; i++) {
		if (cnt[i] == 0) continue;
		int cur = S.query(cnt[i] - 1) + C.queryRange(cnt[i], n) * (cnt[i] - 1);
		ans = max(ans, cur + cnt[i]);
		S.update(cnt[i], cnt[i]);
		C.update(cnt[i], 1);
	}
	cout << n - ans << '\n';
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	int t; cin >> t; while (t-- > 0) solve();
	return 0;
}